package com.haohuo.framework.mybatisplusgen.compose;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.haohuo.framework.mybatisplusgen.PropertyUtil;

import java.io.File;

public class ComposeConfig  extends FileOutConfig {

    private static final String SUFFIX = "Compose";

    public String outputDir;
    public PackageConfig packageConfig;

    public ComposeConfig(String template,String outputDir,PackageConfig packageConfig){
        super(template == null ? template : template + ".ftl");
        this.outputDir = outputDir;
        this.packageConfig = packageConfig;
    }

    @Override
    public String outputFile(TableInfo tableInfo) {
        String composeName = tableInfo.getEntityName() + SUFFIX;
        String compose = joinPath(outputDir, joinPackage(packageConfig.getParent(), PropertyUtil.getProp("composePkgName")));
        return String.format((compose + File.separator + "%s" + ConstVal.JAVA_SUFFIX), composeName);
    }

    private String joinPath(String parentDir, String packageName) {
        if (StringUtils.isBlank(parentDir)) {
            parentDir = System.getProperty(ConstVal.JAVA_TMPDIR);
        }
        if (!StringUtils.endsWith(parentDir, File.separator)) {
            parentDir += File.separator;
        }
        packageName = packageName.replaceAll("\\.", StringPool.BACK_SLASH + File.separator);
        return parentDir + packageName;
    }

    private String joinPackage(String parent, String subPackage) {
        return StringUtils.isBlank(parent) ? subPackage : (parent + StringPool.DOT + subPackage);
    }
}
